import React ,{useState ,useEffect} from 'react';
import style from './EnterpriseEdit.module.scss'
import {useNavigate} from "react-router-dom";
import {notification ,Modal, Upload} from "antd";
//引入请求
import {registerGetCityApi ,registerUpdataApi,getEnterpriseApi} from "../../http/userApi";


//定义弹窗成功提示的一些内容
type NotificationType = 'success' | 'info' | 'warning' | 'error';
const openNotificationWithIcon = (type: NotificationType,msg) => {
    notification[type]({
        message: msg,
        placement:'top',
        duration: 1,
    });
};


//图片上传组件
import { PlusOutlined } from '@ant-design/icons';
import type { RcFile, UploadProps } from 'antd/es/upload';
import type { UploadFile } from 'antd/es/upload/interface';

const getBase64 = (file: RcFile): Promise<string> =>
    new Promise((resolve, reject) => {
        const reader = new FileReader();
        console.log(reader)
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result as string);
        reader.onerror = error => reject(error);
    });






//引入级联选择框
import { Cascader } from 'antd';
//定义弹窗

//定义弹窗失败提示的一些内容
const openNotification = (placement: NotificationPlacement,msg) => {
    notification.info({
        message: msg,
        placement,
        duration: 1,
    });
};


//级联选择框

interface Option {
    value: string | number;
    label: string;
    children?: Option[];
}
function EnterpriseEdit(props) {
    const navigate = useNavigate()

    //点击返回
    const backHandler =()=>{
        navigate(-1)
    }
    const userInfo = {
        corporateName:'',
        city:'',
        adderss:'',
        longitude:'',//经度
        latitude:'',//维度
        briefIntroduction:'',
        servicePhone:'',
        Businesslicense:'',//营业执照
        DoorheadPhoto:'',//门头照片
        name:'',
        phone:'',
        openMap:false
    }
    const [options,setOptions] = useState([]);
    //获取城市
    useEffect(()=>{
        getEnterpriseApi()
            .then(res=>{
                console.log(res.data.data)
                if(res.data.code == 200) {
                    setInput({
                        ...res.data.data
                    })
                    initMap()
                    registerGetCityApi()
                        .then(res=>{
                            setOptions(res.data.data)

                        })
                }
            })

    },[])
    //获取选中的城市
    const onChange = (value: string[]) => {
        setInput({
            ...userInput,city:value
        })
    };
    //设置用户输入的响应式数据
    const [userInput ,setInput] = useState(userInfo)
    //受控组件
    const changeInput = (e) => {
        setInput({
            ...userInput,[e.target.name]:e.target.value
        })
    }

    //提交
    const submitHanlder =()=>{
        if(userInput.corporateName ==''){
            return openNotification(NotificationPlacement,'请输入企业名称')
        }
        if(userInput.city ==[]){
            return openNotification(NotificationPlacement,'请选择省市区')
        }
        if(userInput.adderss ==''){
            return openNotification(NotificationPlacement,'请输入详细地址')
        }
        if(userInput.longitude =='00.00.00'){
            return openNotification(NotificationPlacement,'请标注地址')
        }
        if(userInput.briefIntroduction ==''){
            return openNotification(NotificationPlacement,'请填写公司简介')
        }
        if(userInput.servicePhone ==''){
            return openNotification(NotificationPlacement,'请填写客服电话')
        }
        if(userInput.Businesslicense ==''){
            return openNotification(NotificationPlacement,'请上传营业执照')
        }
        if(userInput.DoorheadPhoto ==''){
            return openNotification(NotificationPlacement,'请上传门店照片')
        }
        if(userInput.name ==''){
            return openNotification(NotificationPlacement,'请填写负责人')
        }
        if(userInput.phone ==''){
            return openNotification(NotificationPlacement,'请填写负责人电话')
        }
        //发起请求
        console.log(userInput)
        registerUpdataApi(userInput)
            .then((res)=>{
                console.log(res.data.code)
                if(res.data.code==200){
                    navigate('/collection/information')
                }
            })
            .catch(err=>{
                console.log('请求失败',err)
            })
    }

    //地图标注
    function initMap() {
        var marker = null;
        var center = new TMap.LatLng(39.984104, 116.307503);//设置中心点坐标

        //初始化地图
        var map = new TMap.Map("container", {
            center: center
        });

        // 初始化marker图层
        var marker = new TMap.MultiMarker({
            id: 'marker-layer',
            map: map
        });
        //移除marker事件
        // 监听点击事件添加marker
        map.on("click", (evt) => {
            setInput({
                ...userInput,longitude:evt.latLng.lat,latitude:evt.latLng.lng
            })
            if(marker){
                marker.setMap(null);
                marker = null;
            }
            marker = new TMap.MultiMarker({
                id: 'marker-layer',
                map: map,
                geometries: [{
                    "id": 'demo',
                    "styleId": 'marker',
                    "position": evt.latLng,
                    "properties": {
                        "title": "marker"
                    }
                }]
            });

        });
    }



    //图片上传
    const [previewVisible, setPreviewVisible] = useState(false);
    const [previewImage, setPreviewImage] = useState('');
    const [previewTitle, setPreviewTitle] = useState('');
    //营业执照
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    //门头照片
    const [fileListDoorhead, setFileListDoorhead] = useState<UploadFile[]>([]);

    const handleCancel = () => setPreviewVisible(false);

    const handlePreview = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewVisible(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };
    //门头照片
    const handlePreviewDoorhead = async (file: UploadFile) => {
        if (!file.url && !file.preview) {
            file.preview = await getBase64(file.originFileObj as RcFile);
        }

        setPreviewImage(file.url || (file.preview as string));
        setPreviewVisible(true);
        setPreviewTitle(file.name || file.url!.substring(file.url!.lastIndexOf('/') + 1));
    };
    const handleChange: UploadProps['onChange'] = ({ fileList: newFileList }) =>{
        setFileList(newFileList);
        setInput({
            ...userInput,Businesslicense:JSON.stringify(newFileList)
        })
        console.log(newFileList)
    }
    const handleChangeDoorhead: UploadProps['onChange'] = ({ fileList: newFileList }) =>{
        setFileListDoorhead(newFileList);
        setInput({
            ...userInput,DoorheadPhoto:JSON.stringify(newFileList)
        })
        console.log(newFileList)
    }

    const uploadButton = (
        <div>
            <PlusOutlined />
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    return (
        <div>
            <div className={style.back} onClick={backHandler}>返回</div>
            <div className={style.header}>修改企业信息</div>
            <div className={style.main}>
                <div className={style.from}>
                    {/*企业名称*/}
                    <div className={style.input_box}>
                        <div className={style.input_name}>企业名称</div>
                        <div className={style.input_view}>
                            <input value={userInput.corporateName} name="corporateName" onChange={(e)=>changeInput(e)}/>
                        </div>
                    </div>
                    {/*注册地址*/}
                    <div className={style.input_box}>
                        <div className={style.input_name}>注册地址</div>
                        <div className={style.input_view}>
                            <div style={{height:'46px'}}><Cascader options={options} onChange={onChange} placeholder="请选择省市区" size="large" style={{marginRight:"3px",width:"160px"}} /></div>
                            <input value={userInput.adderss} name="adderss" onChange={(e)=>changeInput(e)}/>
                        </div>
                    </div>
                    {/*经纬度*/}
                    <div className={style.input_box}>
                        <div className={style.input_name}>经纬度</div>
                        <div className={style.input_view}>
                            <input value={userInput.longitude+','+userInput.latitude} name="email" disabled onChange={(e)=>changeInput(e)}/>
                            <div className={style.biaozhu}>标注</div>
                        </div>
                    </div>

                    {/*标注*/}
                    <div className={style.map} >
                        <div id="container" >
                        </div>
                    </div>


                    {/*企业简介*/}
                    <div className={style.input_box}>
                        <div className={style.input_name}>企业简介</div>
                        <div className={style.input_view}>
                            <textarea value={userInput.briefIntroduction} name="briefIntroduction" onChange={(e)=>changeInput(e)}/>
                        </div>
                    </div>
                    {/*客服电话*/}
                    <div className={style.input_box}>
                        <div className={style.input_name}>客服电话</div>
                        <div className={style.input_view}>
                            <input value={userInput.servicePhone} name="servicePhone" onChange={(e)=>changeInput(e)}/>
                        </div>
                    </div>
                    {/*营业执照*/}
                    <div className={style.input_box}>
                        <div className={style.input_name}>营业执照</div>
                        <div className={style.input_view}>

                            <Upload
                                action="http://127.0.0.1:4523/mock/1088229/storefront/user/register/updataImg"
                                listType="picture-card"
                                fileList={fileList}
                                onPreview={handlePreview}
                                onChange={handleChange}
                            >
                                {fileList.length >= 8 ? null : uploadButton}
                            </Upload>
                            <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                        </div>
                    </div>
                    {/*门头照片*/}
                    <div className={style.input_box}>
                        <div className={style.input_name}>门头照片</div>
                        <div className={style.input_view}>
                            <Upload
                                action="http://127.0.0.1:4523/mock/1088229/storefront/user/register/updataImg"
                                listType="picture-card"
                                fileList={fileListDoorhead}
                                onPreview={handlePreviewDoorhead}
                                onChange={handleChangeDoorhead}
                            >
                                {fileListDoorhead.length >= 8 ? null : uploadButton}
                            </Upload>
                            <Modal visible={previewVisible} title={previewTitle} footer={null} onCancel={handleCancel}>
                                <img alt="example" style={{ width: '100%' }} src={previewImage} />
                            </Modal>
                        </div>
                    </div>
                    <div className={style.input_box}>
                        <div className={style.input_name}>负责人姓名</div>
                        <div className={style.input_view}>
                            <input value={userInput.name} name="name" onChange={(e)=>changeInput(e)}/>
                        </div>
                    </div>
                    <div className={style.input_box}>
                        <div className={style.input_name}>负责人电话</div>
                        <div className={style.input_view}>
                            <input value={userInput.phone} name="phone" onChange={(e)=>changeInput(e)}/>
                        </div>
                    </div>
                </div>
                <div className={style.submit_btn} onClick={submitHanlder}>下一步</div>
            </div>


        </div>
    );
}

export default EnterpriseEdit;

